package cn.edu.njust.control;

import cn.edu.njust.mapper.UserMapper;
import cn.edu.njust.pojo.Register;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;

@WebServlet(name = "registerServlet", value = "/registerServlet")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收用户数据
        String idNo = request.getParameter("exampleInputId_no1");

        Boolean use;
        if ("true".equals(request.getParameter("exampleInputFree1"))) {
            use = true;
        } else {
            use = false;
        }

        //资格需要算，这里现在还不太知道怎么处理
        Boolean admission = true;
        String language = request.getParameter("exampleInputLanguage1");

        System.out.println(idNo);
        System.out.println(request.getParameter("exampleInputFree1"));
        System.out.println(use);
        System.out.println(language);

        //封装用户对象
        Register register = new Register();
        register.setIdNo(idNo);
        register.setIsUse(use);
        register.setAdmission(admission);
        register.setLanguage(language);

        //调用mapper根据用户ID查询对像
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        //调用方法
        Register r = userMapper.selectByIdNo(idNo);

        HttpSession session = request.getSession();

        session.setAttribute("registerUser", register);

        //判断用户对象释放为null
        if (r == null) {
            userMapper.add(register);

            userMapper.add01(idNo);

            //提交事务
            sqlSession.commit();
            //释放资源
            sqlSession.close();
            //完事后跳走
            response.sendRedirect("applyInfo.jsp");
        } else {
            //不可能出现这种情况，所以随便跳啦
            response.sendRedirect("applyInfo.jsp");
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
